package org.itboys.seller.service;

import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseService;
import org.itboys.seller.entity.GetRewardRecord;
import org.itboys.seller.entity.SubManProviderDB;
import org.mongodb.morphia.query.Query;
import org.mongodb.morphia.query.UpdateOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 商家登陆账号
 * @author weisky
 *
 */
@Service
public class SubManProviderService extends BaseService<SubManProviderDB, Long>{
	
	private static final long serialVersionUID = 1L;

	@Resource(name = "sellerDS")
	private MongoDataSource ds;

	@Override
	protected MongoDataSource getMongoDataSource() {
		return ds;
	}

	@Override
	protected Class<SubManProviderDB> getEntityClass() {
		return SubManProviderDB.class;
	}

    public void saveProviderRecord(long fromId, long toId, int score) {
        SubManProviderDB record = ds.createQuery(SubManProviderDB.class).field("fromUserId").equal(fromId)
                .field("toUserId").equal(toId).get();
        if (record == null) {
            record = new SubManProviderDB();
            record.setFromUserId(fromId);
            record.setToUserId(toId);
            record.setScore(score);
            save(record);
            return;
        }
        record.setScore(record.getScore() + score);
        update(record);
    }

    public int getScore(long fromId, long toId) {
        SubManProviderDB record = ds.createQuery(SubManProviderDB.class).field("fromUserId").equal(fromId)
                .field("toUserId").equal(toId).get();
        return record == null ? 0 : record.getScore();
    }

    public void clearScore(long toId) {
        Query<SubManProviderDB> query = ds.createQuery(SubManProviderDB.class)
                .field("toUserId").equal(toId);
        UpdateOperations<SubManProviderDB> ops = ds.createUpdateOperations(SubManProviderDB.class);
        ops.set("score", 0);
        ds.update(query, ops);
        logger.info("获奖人 {} 清空本周期所有下属贡献积分记录", toId);
    }

    public List<SubManProviderDB> getAll() {
        return ds.createQuery(SubManProviderDB.class).asList();
    }

}
